package com.example.demo.entity.queue;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zcb
 * @Description:
 * @Date: 2021/10/22
 */
public class ConditionTaskQueue {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    Queue<String> queue = new LinkedList<>();

    public Lock getLock() {
        return lock;
    }

    public void addTask(String s) {
        try {
            lock.lock();
            queue.add(s);
            //通知等待该锁的所有线程
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public String getTask() throws InterruptedException {
        try {
            lock.lock();
            while (queue.isEmpty()) {
                //等待
                condition.await();
            }
            return queue.remove();
        } finally {
            lock.unlock();
        }
    }
}
